package com.oa.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.oa.pojo.*;
import com.oa.service.UserService;
import com.oa.utils.CommonUtil;
import com.oa.utils.EntityException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @Author Str
 * @Date 2021/12/7 15:13
 * @Description :
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    // 登录页
    @RequestMapping(value = "/showLogin", produces = "text/html;charset=UTF-8")
    public String showLogin() {
        return "login";
    }

    // 欢迎页
    @RequestMapping(value = "/welcome", produces = "text/html;charset=UTF-8")
    public String welcome() {
        return "/user/welcome";
    }

    // 错误页
    @RequestMapping(value = "/error", produces = "text/html;charset=UTF-8")
    public String error() {
        return "error";
    }

    // 没有权限页
    @RequestMapping(value = "/unauthorized", produces = "text/html;charset=UTF-8")
    public String unauthorized() {
        return "unauthorized";
    }

    // 登录
//    @RequestMapping("/login")
//    public String login(
//            @RequestParam("username") String username,
//            @RequestParam("password") String password,
//            HttpSession session) {
//        // 根据用户名查找用户
//        User user = userService.login(username,password);
//        System.out.println(user);
//        // 设置会话域
//        session.setAttribute("user", user);
//        // 内部转发
//        return "index_temp";
//    }

    // 登录
    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password) {
        System.out.println("username:" + username);
        System.out.println("password:" + password);
        //{1}创建令牌, 载入 用户名+密码
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //{2}获取主体对象
        Subject subject = SecurityUtils.getSubject();
        String respTxt = "";
        JSONObject jo = new JSONObject();
        String errcode = "0";
        try {
            //{3}执行登录
            subject.login(token);
            //{4}尝试使用 shiro 提供的 session
            Session session = subject.getSession(true);
            //{5}通过主体获取 [数据库] 中的用户身份信息。
            Object user = subject.getPrincipal();
            //{6}设置到会话域。
            session.setAttribute("user", user);

            if (subject.isPermitted("user:showUserForm")) {
                System.out.println("有权限：user:showUserForm");
            } else {
                System.out.println("没有权限：user:showUserForm");
            }
            Set permissions = (Set) session.getAttribute("permissions");
            System.out.println("==================================");
            System.out.println(permissions);
            System.out.println("==================================");
            jo.put("result", "success");
            respTxt = jo.toJSONString();
            //{7}重定向到 主页(成功)
//            return new ModelAndView("index_temp");
//            return "index_temp";
            // 没有该用户
        } catch (UnknownAccountException e) {
            // 账户不存在异常
            errcode = "1";
            jo.put("result", "failed");
            jo.put("cause", "账户不存在");
            respTxt = jo.toJSONString();
        } catch (IncorrectCredentialsException e) {
            // 密码不存在异常
            errcode = "2";
            jo.put("result", "failed");
            jo.put("cause", "密码不存在");
            respTxt = jo.toJSONString();
        }

        System.out.println("errcode:" + errcode);
//        return new ModelAndView("login","errcode",errcode);
//        return "redirect:showLogin?errcode=" + errcode;
        return respTxt;
    }

    // 跳转到首页
    @RequestMapping(value = "/index", produces = "text/html;charset=UTF-8")
    public String index() {
        return "index_temp";
    }

    //登出
    @RequestMapping(value = "/logout", produces = "text/html;charset=UTF-8")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        // 验证用户是否登录
        if (subject.isAuthenticated()) {
            subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
            System.out.println("用户退出登录");
        }
        return "login";
    }


    //3.1、jsonDeptOptions
    @RequestMapping(value = "/jsonDeptOptions", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String jsonDeptOptions() {
        List<Option> list = userService.getDeptOptions();
        JSONObject jsObj = new JSONObject();
        jsObj.put("deptJson", list);
        return jsObj.toJSONString();
    }

    //3.2、jsonRoleOptions
    @RequestMapping(value = "/jsonRoleOptions", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String jsonRoleOptions() {
        List<Option> list = userService.getRoleOptions();
        JSONObject jsObj = new JSONObject();
        jsObj.put("roleJson", list);
        return jsObj.toJSONString();
    }

    //3.3、/user/viewList
    @RequestMapping("/viewList")
    public String viewList() {
        //{ps}内部转发到:
        //    /WEB-INF/jsp/user/list.jsp
        return "user/list";
    }

    /**
     * data:查找条件
     * page:页数
     * limit:每页数据数
     */
    //3.4、/user/jsonList?page=1&limit=5
    @RequestMapping(value = "/jsonList", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String jsonList(@RequestParam Map<String, String> data,
                           @RequestParam(name = "page", required = true, defaultValue = "1") int page,
                           @RequestParam(name = "limit", required = true, defaultValue = "10") int limit) {
        // 输出data
        CommonUtil.iterateMap(data);
        //{1}获取 PageData 页信息
//        PageData pageData = new PageData(data);
        //{2}调用 userService 获取用户列表
        try {
            Page<User> pages = userService.getUserList(page, limit, data);
            return packJSON(pages);
        } catch (Exception e) {
            e.printStackTrace();
            return setErrorMsg(e);
        }
    }


    // 添加/新增用户页
    @RequestMapping("/showUserForm")
    public String showUserForm() {
        //{ps}内部转发到:
        //    /WEB-INF/jsp/user/list.jsp
        return "user/addUser";
    }

    //3.4、/User/jsonList
    @RequestMapping(value = "/saveUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String saveUser(@RequestParam Map<String, String> data) {
        for (String s : data.keySet()) {
            System.out.println("key:" + s + ",value:" + data.get(s));
        }

        JSONObject jsObj = new JSONObject();
        String respTxt = "";
        try {
            userService.saveUser(data);
            jsObj.put("result", "success");
            respTxt = jsObj.toString();
        } catch (EntityException e) {
            e.printStackTrace();
            respTxt = setErrorMsg(e);
        }
        return respTxt;
    }

    // 根据ID获取用户
    @RequestMapping(value = "/getUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getUser(@RequestParam("userId") String userId) {
        Map<String, Object> map = new HashMap<>();
        User user = null;
        JSONObject jsObj = new JSONObject();
        String respTxt = "";
        try {
            //{2}根据 id 获取用户
            user = userService.getOne(userId);
            map.put("id", user.getId());
            map.put("username", user.getUsername());
            map.put("password", user.getPassword());
            map.put("nickName", user.getNickName());
            map.put("deptId", user.getDeptId());
            map.put("email", user.getEmail());
            map.put("no", user.getNo());
            map.put("sex", user.getSex());
            map.put("createDate", user.getCreateDate());
            map.put("roleId", user.getPrimaryRole().getId());
            //{3}存入相关信息
            jsObj.put("result", "success");
            jsObj.put("user", map);
            respTxt = jsObj.toString();
        } catch (Exception e) {
            e.printStackTrace();
            respTxt = setErrorMsg(e); //打包错误信息
        }
        return respTxt;
    }

    // 删除用户
    @RequestMapping(value = "/delUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String delUser(@RequestParam("userId") String userId) {
        JSONObject jsObj = new JSONObject();
        String respTxt = "";
        try {
            userService.delUser(userId);
            jsObj.put("result", "success");
            respTxt = jsObj.toString();
        } catch (EntityException e) {
            e.printStackTrace();
            respTxt = setErrorMsg(e);
        }
        return respTxt;
    }

    // 获取用户名与用户昵称数据
    @RequestMapping(value = "/getNickNameData", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getNickNameData() {
        List<Option> options = new ArrayList();
        List<User> users = userService.getAll();
        System.out.println("users==========");
        System.out.println(users);
        // 将楼层和id填充进Option列表
        for (User user : users) {
            Option op = new Option(user.getNickName(), user.getId());
            options.add(op);
        }

        JSONObject jsObj = new JSONObject();
        jsObj.put("result", "success");
        jsObj.put("options", options);
        return jsObj.toJSONString();
    }
}
